package com.example.demo;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 自定义序列化类
 *
 * @since 2024/3/6 13:02
 */
@AllArgsConstructor
@NoArgsConstructor
public class DesensitizationSerialize extends JsonSerializer<LocalDateTime> implements ContextualSerializer {

    private String pattern;


    @Override
    public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException {
        gen.writeObject(value);
        if (value != null) {
        gen.writeFieldName(gen.getOutputContext().getCurrentName() + "View");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
            LocalDate localDate = value.toLocalDate();
            String formattedDate = localDate.format(formatter);
            gen.writeObject(formattedDate);
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty != null) {
            Desensitization desensitization = beanProperty.getAnnotation(Desensitization.class);
            if (desensitization != null) {
                return new DesensitizationSerialize(desensitization.value());
            }
        }
        return serializerProvider.findNullValueSerializer(null);
    }
}
